<template>
  <div style="height: 100%" v-loading="loading">
    <van-nav-bar
        title="吨槽调整信息"
        left-text="返回"
        left-arrow
        @click-left="goBack"
        :right-text="postingDate"
        @click-right="setPostDate"
    />
    <van-cell-group
        :v-model="tableData"
        style="overflow: scroll; height: 520px"
    >
      <van-field
          v-model="code_input"
          ref="code_input"
          placeholder="请扫描条码"
          left-icon="scan"
          @input="onSubmitScanResult"
      />

      <van-swipe @change="onChange" width="100%" ref="swiper" style="border: solid #3793fb 1px;border-top:none">
        <van-swipe-item v-for="(domain, domainIndex) in tableData.details" :key="domainIndex" >
          <van-button @click="onDeleteBarrel(domainIndex)" class="custom-swipe-delete" v-if="current >= 0"
                      color="linear-gradient(to right, #ff6034, #ee0a24)">
                      删除
          </van-button>
          <van-field v-model="domain.numberofbarrels" label="桶号" readonly></van-field>
          <van-field v-model="domain.bucketstatus" label="当前桶状态" readonly></van-field>
          <van-field v-model="domain.customername" label="客户名称：" readonly/>
          <van-field v-model="domain.commodityname" label="商品名称：" readonly/>
          <van-field v-model="domain.packinglotno"  label="包装批："  readonly/>
          <van-row style="border: solid 1px #3793fb; border-radius: 5px">
            <van-col span="24">
              <el-autocomplete id="autocomplete" v-model="domain.locationAll" value-key="codeanddes" @input="onInput"
                               label="发出库位" :rules="{ required: true, message: '请选择库位', trigger: 'blur',
                  }" :fetch-suggestions="storageLocationSearch" placeholder="发出库位" style="width: 100%;"></el-autocomplete>
            </van-col>
          </van-row>
<!--          <van-field v-model="domain.location" label="库位" readonly></van-field>-->
<!--          <van-field v-model="domain.locationdes" label="库位描述" readonly></van-field>-->
<!--          <van-field v-model="domain.leftovers" label="余重"  @input="quantityChange" readonly></van-field>-->
          <van-radio-group v-model="domain.adjuststatus">
            <van-cell-group inset>
              <van-cell title="借用" clickable @click="checked(domain.adjuststatus , domain.bucketstatus , domainIndex)">
                <template #right-icon>
                  <van-radio name="借用" />
                </template>
              </van-cell>
              <van-cell title="清洗" clickable @click="checked(domain.adjuststatus , domain.bucketstatus , domainIndex)">
                <template #right-icon>
                  <van-radio name="清洗" />
                </template>
              </van-cell>
              <van-cell title="维修" clickable @click="checked(domain.adjuststatus , domain.bucketstatus , domainIndex)">
                <template #right-icon>
                  <van-radio name="维修" />
                </template>
              </van-cell>
              <van-cell title="报损" clickable @click="checked(domain.adjuststatus , domain.bucketstatus , domainIndex)">
                <template #right-icon>
                  <van-radio name="报损" />
                </template>
              </van-cell>
              <van-cell title="封存" clickable @click="checked(domain.adjuststatus , domain.bucketstatus , domainIndex)">
                <template #right-icon>
                  <van-radio name="封存" />
                </template>
              </van-cell>
              <van-cell title="空闲" clickable @click="checked(domain.adjuststatus , domain.bucketstatus , domainIndex)">
                <template #right-icon>
                  <van-radio name="空闲" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
        </van-swipe-item>
        <template #indicator>
          <div class="custom-indicator" v-if="current >= 0">{{ current + 1 }}/{{ totalSize }}</div>
        </template>
      </van-swipe>
    </van-cell-group>

    <van-button
        @click="onSubmit"
        style="
        position: fixed;
        bottom: 0px;
        border: #3793fb solid 1px;
        border-radius: 2px;
        background-color: #3793fb;
        line-height: var(--footer-height);
      "
        type="primary"
        block
    >吨槽调整</van-button
    >
  </div>
</template>

<script>
// import Keyboard  from "../../assets/views/vnp-keyboard.vue";
export default {
  // components: { 'vnp-keyboard': Keyboard, },
  data() {
    return {
      tableData: {
        details: []
      },
      storageLocationList: [],
      loading: false,
      index: 0,
      totalSize: 0,
      current: -1,
      code_input: '',
      dc_flag:false,
      showCalendar: false,
      postingDate: this.getNowFormatDate(new Date()),
      minDate:this.getMonthBeforeDate(),
      maxDate:this.getMonthAfterDate()
    };
  },
  mounted() {
    //获取库位List
    this.getStorageLocationList();
  },
  methods: {
    onSubmitScanResult(event){
      this.getBucket(event);
    },
    async getBucket(bucketNo) {
      let scanInfo = {
        code: bucketNo,
      };
      const { data: res } = await this.$http.post(
          "/RecycleToneSlotsList",
          scanInfo
      );
      console.log("res",res);
       if (res.length && res[0].numberofbarrels) {
        var requestData = this.tableData;
        for (var i in requestData.details) {
          if(requestData.details[i].code === res[0].code){
            this.$message({
              message: "扫描失败，请勿重复扫描同一条码",
              type: "error",
            });
            this.code_input = '';
            return
          }
        }
        // if('占用' !== res[0].bucketstatus){
        //   this.$toast.fail('条码信息错误,非占用状态');
        //   this.code_input = '';
        //   return
        // }
        var specification = res[0].leftovers;
        this.tableData.details.push({ numberofbarrels: res[0].numberofbarrels,
                                      bucketstatus: res[0].bucketstatus,
                                      // location: res[0].location,
                                      // locationdes: res[0].locationdes,
                                      locationAll: res[0].location+"|"+res[0].locationdes,
                                      leftovers: res[0].leftovers,
                                      packinglotno: res[0].packinglotno,
                                      commodityname: res[0].commodityname,
                                      customername: res[0].customername,
                                      code: res[0].code
        });
        this.tableData.noofbarrels = parseInt(this.tableData.noofbarrels) + 1;
        this.tableData.totalquantity = parseInt(this.tableData.totalquantity) + parseInt(specification);
        this.totalSize = this.tableData.details.length;
        this.current = this.totalSize - 1;
        this.$refs.swiper.swipeTo(this.current);
        this.code_input = '';
      } else {
        this.code_input = '';
        if(res.length){
          this.$toast.fail(res[0].message);
        }else{
          this.$toast.fail('条码信息错误');
        }
      }
    },
    onDeleteBarrel(domainIndex) {
      this.tableData.totalquantity -= this.tableData.details[domainIndex].leftovers;
      this.tableData.details.splice(domainIndex, 1);
      this.tableData.noofbarrels -= 1;
      this.totalSize = this.tableData.details.length;
      if (this.current > this.totalSize - 1) {
        this.current = this.totalSize - 1;
      }
      this.$refs.swiper.swipeTo(this.current);
    },
    checked(adjuststatus,bucketstatus,domainIndex) {
       if(adjuststatus !== '空闲' && (bucketstatus == '在途' || bucketstatus == '借用' || bucketstatus == '维修'
                                 || bucketstatus == '报损' || bucketstatus == '封存' ) ){
        this.$toast.fail('桶状态只能转空闲');
        this.tableData.details[domainIndex].adjuststatus = '';
        return
       }
      if(adjuststatus == '维修' && bucketstatus == '空闲'){
        this.$toast.fail('空闲状态需先清洗再维修');
        this.tableData.details[domainIndex].adjuststatus = '';
        return
      }
      if(bucketstatus == '清洗' && (adjuststatus == '借用' || adjuststatus == '清洗' || adjuststatus == '报损' || adjuststatus == '封存') ){
        this.$toast.fail('清洗状态只能转空闲/维修');
        this.tableData.details[domainIndex].adjuststatus = '';
        return
      }
    },
    quantityChange(){
      var total = 0;
      for( var i in this.tableData.details){
        if(this.tableData.details[i].leftovers !== ''){
          total +=  parseInt(this.tableData.details[i].leftovers);
        }
        this.tableData.totalquantity = total;
      }
    },
    onFocus() {
      this.showKeyboards = true;
    },
    getcrNumber(val) {
      const carNumberReg =
          /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/;
      if (carNumberReg.test(val)) {
        this.showKeyboards = false;
        this.carNumber = val;
      }
    },
    //返回
    goBack() {
      this.$router.push("/HomePage");
    },
    //入库过账
    onSubmit() {
      this.loading = true;
      setTimeout(() =>{
        this.loading = false;
        this.AdjustToneSlotsPost();
      }, 1000);
    },
    async AdjustToneSlotsPost(){
      var requestData = this.tableData;
      var recycledata = [];
      for (var i in requestData.details) {
        recycledata.push({
          numberofbarrels: requestData.details[i].numberofbarrels,
          bucketstatus: requestData.details[i].adjuststatus,
          // location: requestData.details[i].location,
          // locationdes: requestData.details[i].locationdes,
          location: requestData.details[i].locationAll.split("|")[0],
          locationdes: requestData.details[i].locationAll.split("|")[1],
          leftovers: requestData.details[i].leftovers,
        });
      }
      let inputInfo = {
        plant: localStorage.getItem("plant"),
        postdate:this.postingDate,
        persnumber:localStorage.getItem("erpId"),
        recycledata: recycledata,
      };
      console.log("res22",inputInfo);
      const { data: res } = await this.$http.post(
          "/AdjustToneSlotsPost",
          inputInfo
      );
      var response = res[0];
      if (response.type == "S") {
        this.$toast.success(response.message);
        setTimeout(() => {
          this.$router.push("/HomePage");
        }, 1000);
      } else if (response.type == "E") {
        this.$message({
          message: response.message,
          type: "error",
        });
      } else {
        this.$message({
          message: "移库失败，请联系系统维护人员",
          type: "error",
        });
      }
    },
    onInput(value) {
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
        console.log('输入的内容是：', value);
      }, 0);
    },
    //库位搜索帮助
    storageLocationSearch(queryString, cb) {
      var storageLocationList = this.storageLocationList;
      var results = queryString
          ? storageLocationList.filter(this.createFilter(queryString))
          : storageLocationList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (storageLocation) => {
        return (
            storageLocation.codeanddes
                .toLowerCase()
                .indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    async getStorageLocationList() {
      let scanInfo = {
        plant: localStorage.getItem("plant"),
      };
      const { data: res } = await this.$http.post(
          "/StorageLocationList",
          scanInfo
      );
      this.storageLocationList = res;
    },
    onChange(index) {
      this.current = index;
    },
  },
};
</script>
<style>
.autocompleteLabel {
  -webkit-box-flex: 0;
  -webkit-flex: none;
  flex: none;
  box-sizing: border-box;
  width: 6.2em;
  margin-right: 12px;
  color: #646566;
  text-align: left;
  word-wrap: break-word;
}

.custom-indicator {
  position: absolute;
  right: 5px;
  bottom: 5px;
  padding: 2px 5px;
  font-size: 12px;
  background: rgba(0, 0, 0, 0.1);
}

.custom-swipe-delete {
  font-size: 12px;
  height: 40%;
  margin-left: 5%;
}
</style>